package com.doufeng.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doufeng.base.entity.Role;
import com.doufeng.base.service.RoleService;
import com.doufeng.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/base/role")
public class RoleController {
    
    @Autowired
    private RoleService roleService;
    
    /**
     * 新增角色
     * @param role 角色信息
     * @return 结果
     */
    @PostMapping("/add")
    public Result add(@RequestBody Role role) {
        boolean save = roleService.save(role);
        if (save) {
            return Result.success(null);
        } else {
            return Result.fail(500, "新增失败");
        }
    }
    
    /**
     * 删除角色
     * @param id 角色ID
     * @return 结果
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Long id) {
        boolean remove = roleService.removeById(id);
        if (remove) {
            return Result.success(null);
        } else {
            return Result.fail(500, "删除失败");
        }
    }
    
    /**
     * 分页查询角色
     * @param page 页码
     * @param limit 每页数量
     * @param roleName 角色名称（可选）
     * @return 分页结果
     */
    @GetMapping("/page")
    public Result page(@RequestParam(value = "page", defaultValue = "1") Long page,
                       @RequestParam(value = "limit", defaultValue = "10") Long limit,
                       @RequestParam(value = "roleName", required = false) String roleName) {
        Page<Role> rolePage = new Page<>(page, limit);
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(roleName != null, Role::getRoleName, roleName);
        queryWrapper.eq(Role::getDeleted, 0); // 只查询未删除的记录
        queryWrapper.orderByDesc(Role::getCreateTime);
        roleService.page(rolePage, queryWrapper);
        return Result.success(rolePage);
    }
}